package com.central.user.service.impl;

import com.central.common.feign.ProjectService;
import com.central.common.model.SysDepartment;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.user.mapper.SysDepartmentMapper;
import com.central.user.service.ISysDepartmentService;
import com.central.user.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Tindy
 * @date 2021/6/22
 * @describe
 */
@Slf4j
@Service
public class SysDepartmentServiceImpl extends SuperServiceImpl<SysDepartmentMapper, SysDepartment> implements ISysDepartmentService {

	@Resource
	private ISysUserService userService;
	@Autowired
	private ProjectService projectService;

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void removeById(Long id) throws Exception {
		//判断是否有子部门
		if(findSubs(id).size()>0){
			throw new Exception("存在子部门");
		};
		//判断是否被用户引用
		if(userService.countByDepartmentId(id)>0){
			throw new Exception("被用户引用");
		}
		//判断是否被项目引用
		if(projectService.countByDepartmentId(id)>0){
			throw new Exception("被项目引用");
		}
		baseMapper.deleteById(id);
	}

	@Override
	public List<SysDepartment> findOnes() {
		return baseMapper.findSubs(-1l);
	}

	@Override
	public List<SysDepartment> findSubs(Long id) {
		return baseMapper.findSubs(id);
	}

	@Override
	public SysDepartment findParent(Long id) {
		return null;
	}

	@Override
	public SysDepartment findByUserId(Long userId) {
		return baseMapper.findByUserId(userId);
	}

	@Override
	public String fullName(Long departmentId) {
		SysDepartment department = baseMapper.selectById(departmentId);
		List<Long> parentIds = department.getParentIds();
		StringBuilder fullName=new StringBuilder();
		for (Long parentId : parentIds) {
			SysDepartment parentDepartment = baseMapper.selectById(parentId);
			if (parentDepartment!=null){
				fullName.append(parentDepartment.getName()).append("-");
			}
		}
		fullName.append(department.getName());
		return fullName.toString();
	}

	@Override
	public Map<String, SysDepartment> findDepartmentMap() {
		List<SysDepartment> all = baseMapper.selectList(null);
		HashMap<String, SysDepartment> map = new HashMap<>();
		for (SysDepartment department : all) {
			map.put(department.getId().toString(),department);
		}
		return map;
	}
}
